{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "238f31e3",
   "metadata": {},
   "source": [
    "# 02 Matmul\n",
    "矩阵乘法示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f8a17ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import triton\n",
    "import triton.language as tl\n",
    "\n",
    "@triton.jit\n",
    "def matmul_kernel(A_ptr, B_ptr, C_ptr, M: tl.constexpr, N: tl.constexpr, K: tl.constexpr):\n",
    "    pid = tl.program_id(0)\n",
    "    if pid < M*N:\n",
    "        row = pid // N\n",
    "        col = pid % N\n",
    "        sum = 0.0\n",
    "        for k in range(K):\n",
    "            sum += tl.load(A_ptr + row*K + k) * tl.load(B_ptr + k*N + col)\n",
    "        tl.store(C_ptr + row*N + col, sum)\n",
    "\n",
    "M, N, K = 32, 32, 32\n",
    "A = torch.randn(M, K, device='cuda')\n",
    "B = torch.randn(K, N, device='cuda')\n",
    "C = torch.zeros(M, N, device='cuda')\n",
    "matmul_kernel[(M*N,)](A, B, C, M=M, N=N, K=K)\n",
    "print(\"C[:2,:2] =\", C[:2,:2])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0rc1"
  },
  "title": "Matmul"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
